import { Component, OnInit, ViewChild } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { CropperComponent } from 'angular-cropperjs';
import { routerTransition } from '../router.animations';
import { CountryUtilsService } from '../shared/services/country-utils.service';
import { FileUpload } from 'primeng/fileupload';
import { ConstantVariable, UserRoles, UserStatus, PropertySaleStatus, PropertyType, ContentModuleKeys } from '../shared/config/app-settings';
import { Router } from '@angular/router';
import * as _ from 'lodash';
import { AttachmentUtilsService } from '../shared/services/attachment-utils.service';
import { state } from '@angular/animations';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { Message, SelectItem, ConfirmationService } from 'primeng/api';
import {MenuItem} from 'primeng/api';
import { TranslateService } from '@ngx-translate/core';
import { UserService } from '../shared/services/user.service';
import { MessageUtilsService } from '../shared/services/message-utils.service';
import { ContentService } from '../layout/admin/service/content.service';
import {CountryAutoUtilsService} from '../shared/services/country-auto-utils.service';

@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.scss'],
    animations: [routerTransition()]
})
export class SignupComponent implements OnInit {
    @ViewChild('angularCropper')
    public angularCropper: CropperComponent;

    isCorporate: boolean = false;
    query: string;
    //ui controls
    cdropDownOptions = this.countryUtilsService.dropDownOptions;
    cdropDownSelected = this.countryUtilsService.dropDownSelected;
    cdropDownSuggestions  = {
        countryList: [],
        stateList: [],
        cityList: []
    };
    experienceList: Array<any> = [];
    experienceSelected: any = {}
    msgs: Message[] = [];
    userform: FormGroup;
    genders: SelectItem[];
    sampleImages: any[];
    display = false;
    checked: false;
    editImage: any = '';
    editImageFile: any = null;
    bUploading:boolean = false;
    editImageIndex: number = 0;
    sureEditImage: any = document.getElementsByClassName('cropper-crop-box');

    editImageConfig: any = {
        checkCrossOrigin: false,
    };
    editImageStyle: any = {
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translateX(-50%) translateY(-50%)',
    };
    //models
    tcText;
    currentProfile: any = {};
    step: string = "1";
    emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
    constructor(private countryUtilsService: CountryAutoUtilsService, private userService: UserService,
        private router: Router,
        private confirmationService: ConfirmationService,
        private messageUtilsService:MessageUtilsService,
        private translateService:TranslateService,
        private attachmentUtilsService: AttachmentUtilsService,
        private contentService:ContentService,
        private fb: FormBuilder,
        private sanitizer: DomSanitizer) { }

    ngOnInit() {
        this.experienceList = [
            { label: this.translateService.instant('None'), value: 'None' },
            { label: this.translateService.instant('1-2 Years'), value: '1-2 Years' },
            { label: this.translateService.instant('2-5 Years'), value: '2-5 Years' },
            { label: this.translateService.instant('5+ Years'), value: '5+ Years' }
        ];

        this.genders = [
            { label: this.translateService.instant('Select Title'), value: '' },
            { label: this.translateService.instant('Prof'), value: 'Prof' },
            { label: this.translateService.instant('Dr'), value: 'Dr' },
            { label: this.translateService.instant('Mr'), value: 'Mr' },
            { label: this.translateService.instant('Mrs'), value: 'Mrs' },
            { label: this.translateService.instant('Ms'), value: 'Ms' }
        ];
        this.currentProfile = UserService.defaultProfile;
        this.countryUtilsService.constructDropDownOptions();

        this.userform = this.fb.group({
            'firstName': new FormControl('', Validators.required),
            'lastName': new FormControl('', Validators.required),
            // 'password': new FormControl('', Validators.required),
            'privateEmail': new FormControl('', Validators.compose([Validators.required, Validators.email])),
            // 'password': new FormControl('', Validators.compose([Validators.required, Validators.minLength(6)])),
            'suburb': new FormControl(''),
            'referID': new FormControl('', Validators.compose([Validators.required, Validators.pattern('^(?:i)800[0-9]+$')])),
            'referSurname': new FormControl('', Validators.required),
            'mobile': new FormControl(''),
            'country': new FormControl('', [Validators.required, Validators.maxLength(255)]),
            'state': new FormControl('', [Validators.required, Validators.maxLength(255)]),
            'city': new FormControl('', [Validators.required, Validators.maxLength(255)]),
            'street': new FormControl(''),
            'occupation': new FormControl('', Validators.required),
            'position': new FormControl(''),
            'company': new FormControl(''),
            'experience': new FormControl(''),
            'userType': new FormControl(''),
            'gender': new FormControl('', Validators.required)
        });

        this.sampleImages = [];
        this.sampleImages.push({source: '/assets/img/reg-sample-bad-big-1.jpg',
          thumbnail: '/assets/img/reg-sample-bad-small-1.jpg', title: 'Wearing sunglasses'});
        this.sampleImages.push({source: '/assets/img/reg-sample-bad-big-2.jpg',
          thumbnail: '/assets/img/reg-sample-bad-small-2.jpg', title: 'Closed eyes'});
        this.sampleImages.push({source: '/assets/img/reg-sample-good-big.jpg',
          thumbnail: '/assets/img/reg-sample-good-small.jpg', title: 'Good'});
    }


    //ui-event
    onSearch() {
        if (_.startsWith(this.query, "i8")) {
            this.loadExternalUser(this.query);
            this.step = "1";
        }
        else {
            this.loadUser(this.query);

        }
    }

    onFileUpload(belongToCategory, fileUploader) {
        let attachment = {
            belongToID: this.currentProfile.id,
            belongToCategory: belongToCategory,
            files: fileUploader.files
        };
        this.bUploading = true;
        this.attachmentUtilsService.uploadFile(attachment).subscribe(
            (res) => {
                this.messageUtilsService.showInfo(this.msgs,"Upload file success");
                fileUploader.clear();
                this.loadUser(this.currentProfile.id);
                this.bUploading = false;
            },
            (err) => {
                console.log(err);
                this.messageUtilsService.showError(this.msgs,"Operation Failed.");
                this.bUploading = false;
            }
        );
    }

    onDeleteFile(attachment) {
        this.attachmentUtilsService.deleteFile(attachment.id).subscribe(
            (res) => {
                this.messageUtilsService.showInfo(this.msgs,attachment.originalFilename + " delete success");
                this.loadUser(this.currentProfile.id);
            },
            (err) => {
                console.log(err);
                this.messageUtilsService.showError(this.msgs,"Operation Failed.");
            }
        );
    }

    onRreshDropDownOptions(event?) {
        this.cdropDownSelected.countrySelected = this.userform.get("country").value;
        this.cdropDownSelected.stateSelected = this.userform.get("state").value;
        this.cdropDownSelected.citySelected = this.userform.get("city").value;
        this.countryUtilsService.refreshDropDownOptions();

        console.log(this.cdropDownSelected);
    }

    filterCountries (event) {
        this.cdropDownSuggestions.countryList = [];
        for(let i = 0; i < this.cdropDownOptions.countryList.length; i++) {
            const country = this.cdropDownOptions.countryList[i];
            if(country.toLowerCase().indexOf(event.query.toLowerCase()) === 0) {
                this.cdropDownSuggestions.countryList.push(country);
            }
        }
        this.onRreshDropDownOptions();
    }

    filterStates (event) {
        this.cdropDownSuggestions.stateList = [];
        for(let i = 0; i < this.cdropDownOptions.stateList.length; i++) {
            const state = this.cdropDownOptions.stateList[i];
            if(state.toLowerCase().indexOf(event.query.toLowerCase()) === 0) {
                this.cdropDownSuggestions.stateList.push(state);
            }
        }
        this.onRreshDropDownOptions();
    }

    filterCities (event) {
        this.cdropDownSuggestions.cityList = [];
        for(let i = 0; i < this.cdropDownOptions.cityList.length; i++) {
            const city = this.cdropDownOptions.cityList[i];
            if(city.toLowerCase().indexOf(event.query.toLowerCase()) === 0) {
                this.cdropDownSuggestions.cityList.push(city);
            }
        }
        this.onRreshDropDownOptions();
    }

    onSubmit(userValues?) {
        this.draft();
    }
    tcShow() {
        this.display = true;
        this.contentService.getContent([ContentModuleKeys.TC]).subscribe(
            (res)=>{
                this.tcText = res[0].content1;
        });
    }



    complete() {
        this.userService.applySubmit(this.currentProfile.id).subscribe(
            (res) => {
                console.log(res);
                alert('Register completed, please wait for admin approval by Email.\n' +
                'Please keep eyes on your Email including junk mail folder.');
                this.router.navigate(['/login']);
            },
            (err) => {
                this.messageUtilsService.showError(this.msgs, 'Operation Failed.');
                console.log(err);
            }
        );
    }
    draft() {
        this.enrichRequestBody();

        console.log(this.currentProfile);
        this.userService.getUserList({'code':this.userform.value["referID"],'lastName':this.userform.value["referSurname"]}).subscribe(
            (res)=>{
               if(_.isEmpty(res)){
                    this.messageUtilsService.showError(this.msgs,"ReferID and Name not matched");
               } else{
                this.userService.registerUser(this.currentProfile).subscribe(
                    (res) => {
                        console.log(res);
                        this.messageUtilsService.showInfo(this.msgs,"Please provide photo and certificate in below area!");
                        this.currentProfile = res.data;
                        this.query = this.currentProfile.id;
                        this.scrollToTop();
                        this.step = "2";
                    },
                    (err) => {
                        this.messageUtilsService.showError(this.msgs,err.error.msg);
                        this.step = "1";
                        console.log("Create user failed! " + err);
                    }
                );
               }
            }
        );

    }



    loadExternalUser(code) {
        this.userService.getExternalUser(code).subscribe(
            (res)=>{
                this.currentProfile = res;
                this.countryUtilsService.dropDownSelected = {
                    countrySelected: this.currentProfile.country,
                    stateSelected: this.currentProfile.state,
                    citySelected: this.currentProfile.city
                }
                this.onRreshDropDownOptions()
                this.userform.setValue({
                    firstName: this.currentProfile.firstName,
                    lastName: this.currentProfile.lastName,
                    privateEmail: this.currentProfile.privateEmail,
                    referID: this.currentProfile.referID,
                    mobile: this.currentProfile.mobile,
                    country: this.currentProfile.country,
                    state: this.currentProfile.state,
                    city: this.currentProfile.city,
                    street:this.currentProfile.street,
                    // password: '',
                    occupation: '' ,
                    position: this.currentProfile.position,
                    company:this.currentProfile.company,
                    experience: this.currentProfile.experience,
                    gender: this.currentProfile.sex
                });
                this.step = "1";
            },
            (err)=>{
                console.log(err);
            }
        )
    }

    loadUser(id) {
        let filter = { id: id, status: UserStatus.DRAFT, _v: this.userService.getHash() };
        this.userService.getUserList(filter).subscribe(
            (res) => {
                if (_.isEmpty(res)) {
                    alert("no user found.");
                    this.currentProfile = {};
                } else {
                    this.currentProfile = res[0];
                    this.scrollToTop();
                    this.step = "2";
                }
            },
            (err) => {
                console.log(err);
            }
        );
    }
    //utils
    enrichRequestBody(){
        this.currentProfile = this.userform.value;
        this.currentProfile.role = UserRoles.AGENT;
        this.currentProfile.status = UserStatus.DRAFT;
        this.currentProfile.userType = this.currentProfile.userType ? '1' : '0';
    }

    validBasicInfo(){
        let msg = "";

    }


    validateUpload(){
        return this.isAlreadyUplaodedPhoto() && !_.isEmpty(this.currentProfile['user_attachments']);
    }

    isAlreadyUplaodedPhoto(){
        return _.isEmpty(this.currentProfile['user_portrait'])?false : true;
    }


    scrollToTop() {
        window.scrollTo(0, 0);
    }

    sanitize(url: string) {
        return this.sanitizer.bypassSecurityTrustUrl(url);
    }

    onEditPhoto({
        target,
    }, file, container) {
        const { className, tagName } = target;
        if (/img/i.test(tagName) && className.indexOf('ng-star-inserted') > -1) {
            this.editImage = this.sanitize(target.src);
            this.editImageFile = file;
            if (container) {
                const imgList = [].slice.call(container.querySelectorAll('img.ng-star-inserted'));
                if (imgList && imgList.length) {
                    const index = imgList.indexOf(target);
                    if (index > -1) {
                        this.editImageIndex = index;
                    }
                }
            } else {
                this.editImageIndex = 0;
            }
        }
    }

    clearEditImage() {
        this.editImage = null;
    }

    onEditImageReady() {
        this.sureEditImage[0].addEventListener('dblclick', (e) => {
            if (this.angularCropper && this.angularCropper.cropper && this.editImageFile) {
                const fileName = this.editImageFile.files[this.editImageIndex].name;
                const newFile = this.dataURLtoFile(this.angularCropper.cropper.getCroppedCanvas().toDataURL('image/jpg'), fileName);
                Object.defineProperty(newFile, 'objectURL', {
                    value: this.sanitize(URL.createObjectURL(newFile)),
                    enumerable: true,
                });
                this.editImageFile.files[this.editImageIndex] = newFile;
                this.clearEditImage();
            }
        }, {
            once: true,
        });
    }

    dataURLtoFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    }

}
